//
//  Birthday.swift
//  BirthdayManager
//
//  Created by Apple on 2020/12/16.
//  Copyright © 2020 Charles. All rights reserved.
//

import Foundation
import UIKit
class birthday: NSObject, NSCoding{
    static let userPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first! + "/birthdays.data"
    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name,forKey: "nameKey")
        aCoder.encode(self.date, forKey: "dateKey")
        aCoder.encode(self.count, forKey: "countKey")
        aCoder.encode(self.avatar, forKey: "avatarKey")
        aCoder.encode(self.year, forKey: "yearKey")
    }
    
    required init?(coder aDecoder: NSCoder) {
        name = (aDecoder.decodeObject(forKey: "nameKey") as? String)!
        date = (aDecoder.decodeObject(forKey: "dateKey") as? String)!
        count = (aDecoder.decodeObject(forKey: "countKey") as? String)!
        avatar = (aDecoder.decodeObject(forKey: "avatarKey") as? UIImage)
        year = (aDecoder.decodeObject(forKey: "yearKey") as? String)!
        
    }
    
    func computeCount(dateString: String) -> String {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
        let date = dateStringFormatter.date(from: dateString)
        self.dayFormat = date!
        let cal = Calendar.current
        let today = cal.startOfDay(for: Date())
        let daymonth = cal.dateComponents([.day, .month], from: date!)
        let next = cal.nextDate(after: today, matching: daymonth, matchingPolicy: .nextTimePreservingSmallerComponents)
        let diff = cal.dateComponents([.day], from: today, to: next!)
        //print(String(diff.day!))
//        if String(diff.day!) "365"{
//            return "0"
//        }
        
        return String(diff.day!)
    }
    
    func computeYear(dateString: String) -> String {
        let now = Date()
        let calendar = Calendar.current
        let year = calendar.dateComponents([.year, .month, .day], from: self.dayFormat!, to: now)
        let count = year.year!
        //print(String(count))
        return String(count)
    }
    
    var name: String
    var date: String
    var count: String
    var avatar: UIImage?
    var year: String
    var dayFormat: Date?
    init(name: String, date: String, count: String, avatar: UIImage?) {
        self.name = name
        self.date = date
        self.avatar = avatar
        self.count = count
        self.year = count
        super.init()
        self.count = computeCount(dateString: date)
        self.year = computeYear(dateString: date)
    }
}

